package avicti.bdp;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.List;
import java.util.Map;

/**
 * @金航数码科技有限责任公司
 * @作者：zhangyt
 * @邮箱：zhangyt@avic.com
 * @创建时间： 2024-09-29 17:36
 * @类说明：请填写
 * @修改记录：
 */
public class APITest {
    private static final String CLIENT_ID = "tiBPPfGKMyl5ML8F18F5";
    private static final String CLIENT_SECRET = "WEoWQgR1OUvFn4t1";
    private static final String GET_TOKEN_URL = "http://10.216.40.126:20001/api/bdp/dms/pub/getToken";
    private static final String RESOURCE_URL = "http://10.216.40.126:20001/api/bdp/dms/app/v1/asset/2024/10246?pageNo=1&pageSize=1000";
    public static void main(String[] args) {
         String token=getToken();
         System.out.println("------------>>>>>>>>"+token);
         getMdsBom(token);

    }
    /**
     * 客户端模式获取访问令牌
     * @return token
     */
    public static String getToken(){
        //步骤一：创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //步骤二：创建HTTP请求
        HttpPost httpPost = new HttpPost(GET_TOKEN_URL+"?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&grant_type=client_credentials");
        //步骤三：设置Content-Type为application/x-www-form-urlencoded
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
        try {
            //步骤四：发送请求并获取响应数据
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            ObjectMapper mapper = new ObjectMapper();
            /**
             * 返回结构
             * {
             *  "error_description": "",
             *   "error": "",
             *   "access_token": "accesstoken00001",
             *   "token_type": "Bearer",
             *   "expires_in": "7200"
             * }
             */
            Map<String, String> map = mapper.readValue(result, Map.class);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                String token = map.get("access_token");
                //TODO 客户端根据自身情况实现 需要将token在客户端缓存
               // saveToken(token);
                return token;
            }else{
                throw new RuntimeException(map.get("error_description"));
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(),e);
        }}

    /**
     * 携带访问令牌，访问资源接口http://127.0.0.1:10001/api/demo/getServerTime，获取当前时间
     * @param token
     * @return
     */
    public static Object getMdsBom(String token) {
        //步骤一：创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //步骤二：创建HTTP请求
        HttpGet httpGet = new HttpGet(RESOURCE_URL);
        //步骤三：设置认证token
        httpGet.setHeader("token", token);
        httpGet.setHeader("Content-Type", "application/json");
        try {
            //步骤四：发送请求并获取响应数据
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();
            //如果token失效，则重新申请token
            if (HttpStatus.SC_UNAUTHORIZED == code) {
                String newtoken = getToken();
                return getMdsBom(newtoken);
            }
            String result = EntityUtils.toString(response.getEntity());
            System.out.print("==============>>>>>>>" + result);
            /**
             * 返回结构
             * {
             *  "responseBody": 1695628213913,
             *   "message": "",
             *   "retCode": "200",
             *   "errorDesc": ""
             * }
             */
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(result, Map.class);
            String retCode = (String) map.get("retCode");
            if ("200".equals(retCode)) {
                return (Object) map.get("responseBody");
            } else {
                throw new RuntimeException((String) map.get("errorDesc"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
